package com.yq.design.prototype.deep;


import java.io.*;

/**
 * @ClassName DeepClone
 * @Description 实现序列化，用流的方式序列化和反序列
 * @Author yaoqiang
 * @Date 2021/3/10 15:05
 * @Version 1.0
 */
public class DeepClone implements Serializable{
    private static final long serialVersionUID=1L;

    private String name;

    public Object deepClone() throws IOException {
        //创建流对象：
        ByteArrayOutputStream bos=null;
        ObjectOutputStream oos=null;
        ByteArrayInputStream bis=null;
        ObjectInputStream ois=null;
        try {
            //序列化
            bos=new ByteArrayOutputStream();
            oos=new ObjectOutputStream(bos);
            oos.writeObject(this);//当前这个对象以对象流的方式输出
            //反序列化
            bis=new ByteArrayInputStream(bos.toByteArray());
            ois=new ObjectInputStream(bis);
            DeepClone copyObj= (DeepClone) ois.readObject();
            return copyObj;
        }catch (Exception e){
            return null;
        }finally {
            bos.close();oos.close();bis.close();ois.close();
        }
    }

    public DeepClone(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "DeepClone{" +
                "name='" + name + '\'' +
                '}';
    }
}
